bootbox.setLocale('zh_CN');

function parsePhone(phone){
    var data = {
        'search': '',
        'type': '',
        'searchPre': ''
    };
    if( phone.length <= 10 ){
        data.type = '本地电话';

    }else if(phone.length == 11){
        if( phone[0] == '1' ){
            data.type = '手机';
            data.search = 'mobilepre';
            data.searchPre = phone.substr(0,7);

        }else if( phone[0] == '0' && (phone[1] == '1' || phone[1] == '2') ){
            data.type = '座机';
            data.search = 'areacode';
            data.searchPre = phone.substr(0,3);

        }else if( -1 !==  phone.search(/^0[3-9]/) ){
            data.type = '座机';
            data.search = 'areacode';
            data.searchPre = phone.substr(0,4);

        }else{}
    }else if(phone.length == 12){
        if( phone[0] == '0' && phone[1] == '1'){
            data.type = '手机';
            data.search = 'mobilepre';
            data.searchPre = phone.substr(1,7);


        }else if( -1 !==  phone.search(/^0[3-9]/) ){
            data.type = '座机';
            data.search = 'areacode';
            data.searchPre = phone.substr(0,4);

        }else{
        }

    }else{
    }

    return data;
}

function agentstate(state){
    var $es = $('#exten_status');
    switch (state){
        case 'Unavailable':
            $es.html('<i class="fa fa-circle text-gray"></i> 未注册');
            $('#callbar_call, #callbar_transfer, #callbar_holdon, #callbar_hangup, #callbar_meet, #callbar_score').attr('disabled', 'disabled');
            break;
        case 'Idle':
            $es.html('<i class="fa fa-circle text-success"></i> 空闲');
            if( $('#callbar_holdon').find('span').html() != '恢复' ) $('#callbar_holdon').attr('disabled', 'disabled');
            $('#callbar_transfer, #callbar_hangup, #callbar_meet, #callbar_score').attr('disabled', 'disabled');
            $('#callbar_call').removeAttr('disabled');
            break;
        case 'InUse':
            $es.html('<i class="fa fa-circle text-danger"></i> 通话中');
            $('#callbar_call').attr('disabled', 'disabled');
            $('#callbar_transfer, #callbar_holdon, #callbar_hangup, #callbar_meet, #callbar_score').removeAttr('disabled');
            break;
        case 'Ringing':
            $es.html('<i class="fa fa-circle text-danger"></i> 振铃');
            if( $('#callbar_holdon').find('span').html() != '恢复' ) $('#callbar_holdon').attr('disabled', 'disabled');
            $('#callbar_call, #callbar_meet, #callbar_score').attr('disabled', 'disabled');
            $('#callbar_transfer, #callbar_hangup').removeAttr('disabled');
            break;
        case 'DND':
            $es.html('<i class="fa fa-circle text-warning"></i> 示忙');
            $('#callbar_dnd').attr('disabled', 'disabled');
            $('#callbar_idle').removeAttr('disabled');
            break;
        case 'NotDND':
            $es.html('<i class="fa fa-circle text-success"></i> 示闲');
            $('#callbar_idle').attr('disabled', 'disabled');
            $('#callbar_dnd').removeAttr('disabled');
            break;
        default:
            $('#callbar_call, #callbar_transfer, #callbar_holdon, #callbar_hangup, #callbar_meet, #callbar_score').attr('disabled', 'disabled');
            break;

    }
}

function serverpush(exten){
    $.ajax({
        url: ccIP + "/da/sub?daID=" + exten,
        type: 'GET',
        data: { _: Math.random().toString(36).substring(3, 35) },
        dataType: 'json',
        timeout: 45000,
        error: function(jqXHR,textStatus){
            if( 'timeout' == textStatus ){
                serverpush(exten);
            }else{
                setTimeout(function () {
                    serverpush(exten);
                }, 45000);
            }
        },
        success: function(json){
            serverpush(exten);
            if(json.type == 0){
                agentstate(json.data.state);
            }
            if(json.type == 1){
                popScreen('呼入', json.data, displayClientInfo, json.type);
            }
            if(json.type == 2){
                popScreen('呼出', json.data, displayClientInfo, json.type);
            }
        }
    });
}

function popScreen(calltype, jsonData, callbackFunc, jsonType){
    var  nowtime = Date.now();
    if( nowtime - top.lastPopScreenTime  < top.nextpop_mix_msec  ){
        return;
    }
    top.lastPopScreenTime  =  nowtime;

    var mid = '11';   //【订单客户管理】菜单的id=11
    if( $('iframe[name="iframe-'+ mid +'"]').length===0 ){
        creatNewIframe(mid, "/client/index.html").on('load', function () {
            callbackFunc(mid, calltype, jsonData);
        });
    }else{
        //激活当前iframe
        $('#tab-menu > .tab-item-btn[data-id="iframe-'+ mid +'"]')[0].click();
        callbackFunc(mid, calltype, jsonData);
    }

}

function displayClientInfo(mid, calltype, jsonData){

    var icon = '';
    var phoneInfo = {};
    var phone;
    if(calltype == '呼入'){
        jsonData.calltype = 'in';
        icon = '<b class="glyphicon glyphicon-resize-small call-in"></b> ';

        phone = jsonData.caller;
        phoneInfo = parsePhone(jsonData.caller);
    }else if(calltype == '呼出'){
        jsonData.calltype = 'out';
        icon = '<b class="glyphicon glyphicon-new-window call-out"></b> ';

        phone = jsonData.callee;
        phoneInfo = parsePhone(jsonData.callee);
    }else{
        phone = '';
        phoneInfo = parsePhone('');
    }


    var title = icon + calltype + ( jsonData.QueueNum? '(<b>队列</b>:'+ jsonData.QueueNum +')' : '' ) + (phoneInfo.type==''? '' : '-'+phoneInfo.type);
    if(phoneInfo.search && phoneInfo.searchPre ){
        $.ajax({
            type: 'GET',
            url: ccIP + '/index.php?m=Fast&c=Invoke&a=mobilearea',
            data: { search: phoneInfo.search, searchPre: phoneInfo.searchPre },
            dataType: 'json',
            success: function (json) {
                if(json.result=='success'){
                    $('iframe[name="iframe-'+ mid +'"]')[0].contentWindow.pop (phone, {
                        title: '<span title="' + json.data.city_pinyin + '">' +title + '-'+json.data.province+
                            '<span class="">' +json.data.city+ '</span>(<b>'+ json.data.city_pinyin +'</b>)' +'</span>',
                        ajaxData: {phone:phone, uniqueid:jsonData.uniqueid}
                    });
                }
            }
        });

    }else{
        $('iframe[name="iframe-'+ mid +'"]')[0].contentWindow.pop (phone, {
            title: title,
            ajaxData: {phone:phone, uniqueid:jsonData.uniqueid}
        });

    }
}

//新建 iframe , 参考： \public\admin\js\common.js
function creatNewIframe(mid, url){
    //添加一个tabs
    function addTabs(id) {
        $('.active_tab').removeClass('active_tab');
        var tabs = '<span class="tab-item-btn active_tab" data-id="'+ id +'">'+ $('a[target="'+ id +'"]').text()
            +'&nbsp;<i class="fa fa-close tab-item-close"></i></span>';
        var $tab = $(tabs);
        $('#tab-menu').append($tab);
        return $tab;
    }

    var id = "iframe-"+ mid;
    //新建一个iframe
    var iframe_html  = '<iframe id="'+ id +'" class="default-iframe active-iframe" ' +
        'name="'+ id +'" scrolling="auto" frameborder="0" width="100%" height="100%" src="'+ url +'"></iframe>';
    var $newIframe = $(iframe_html);
    $('#tab-content').append($newIframe);
    addTabs(id).click();    //激活标签
    //当前tab选项卡的长度
    var tab_position_left = $('.tab-item-btn[data-id="'+ id +'"]').position().left;
    var tab_width = $('.tab-item-btn[data-id="'+ id +'"]').outerWidth(true);
    var tabs_width =  tab_position_left + tab_width - $('.tabLeft').outerWidth(true);
    //获取滚动条的left长度
    var tab_menu_scrollLeft = $('#tab-menu').scrollLeft();
    //判断选项卡是否溢出了
    if(tabs_width - $('#tab-menu').width() > 0){
        $('#tab-menu').stop().animate({scrollLeft: tab_menu_scrollLeft+parseFloat(tab_width.toFixed(1))},500);
    }

    return $newIframe;
}

function callbar_dnd(){
    $.ajax({
        type: 'POST',
        url: ccIP + '/index.php?m=Api&c=Exten&a=dnd',
        data: {exten:exten},
        dataType: 'json',
        success: function (json) {
            if(json.result=='success'){
                bootbox.success(json.msg);
                $('#callbar_dnd').attr('disabled', 'disabled');
                $('#callbar_idle').removeAttr('disabled');
            }else{
                bootbox.error(json.msg);
                $('#callbar_dnd').removeAttr('disabled');
                $('#callbar_idle').attr('disabled', 'disabled');
            }
        }
    });

}

function callbar_idle(){
    $.ajax({
        type: 'POST',
        url: ccIP + '/index.php?m=Api&c=Exten&a=idle',
        data: {exten:exten},
        dataType: 'json',
        success: function (json) {
            if(json.result=='success'){
                bootbox.success(json.msg);
                $('#callbar_dnd').removeAttr('disabled');
                $('#callbar_idle').attr('disabled', 'disabled');

            }else{
                bootbox.error(json.msg);
                $('#callbar_dnd').attr('disabled', 'disabled');
                $('#callbar_idle').removeAttr('disabled');
            }
        }
    });

}

function callbar_holdon(){
    $.ajax({
        type: 'POST',
        url: ccIP + '/index.php?m=Api&c=Exten&a=holdon',
        data: {exten:exten},
        dataType: 'json',
        success: function (json) {
            if(json.result=='success'){
                $('#callbar_holdon').find('i').removeClass('fa-spin').next('span').addClass('text-warning').html('恢复');
                bootbox.success(json.msg);

            }else{
                bootbox.error(json.msg);
            }
        }
    });

}

function callbar_restore(){
    $.ajax({
        type: 'POST',
        url: ccIP + '/index.php?m=Api&c=Exten&a=restore',
        data: {exten:exten},
        dataType: 'json',
        success: function (json) {
            if(json.result=='success'){
                $('#callbar_holdon').find('i').addClass('fa-spin').next('span').removeClass('text-warning').html('保持');
                bootbox.success(json.msg);

            }else{
                bootbox.error(json.msg);
            }
        }
    });

}

function callbar_hangup(){
    $.ajax({
        type: 'POST',
        url: ccIP + '/index.php?m=Api&c=Exten&a=hangup',
        data: {exten:exten},
        dataType: 'json',
        success: function (json) {
            if(json.result=='success'){
                bootbox.success(json.msg);

            }else{
                bootbox.error(json.msg);
            }
        }
    });

}

function callbar_score(){
    $.ajax({
        type: 'POST',
        url: ccIP + '/index.php?m=Api&c=Exten&a=score',
        data: {exten:exten},
        dataType: 'json',
        success: function (json) {
            if(json.result=='success'){
                bootbox.success(json.msg);
                $('#callbar_score').attr('disabled', 'disabled');
            }else{
                bootbox.error(json.msg);
            }
        }
    });

}


//工具条事件绑定
$(document).ready(function () {
    $('button.modal-cancel').on("click", function() {
        $(this).parents('div.modal.inmodal').modal('hide');
    });

    $.validator.addMethod('callee_str', function(value, element) {
        return this.optional(element) || /^[a-zA-Z0-9\-]+$/.test(value);
    });
    $.validator.setDefaults({
        highlight: function (element) {
            $(element).parent().parent().removeClass('has-success').addClass('has-error');
        },
        success: function (element) {
            if(element.parent().hasClass('input-group')){
                element.parent().removeClass('has-error').addClass('has-success');
            }else{
                element.parent().parent().removeClass('has-error').addClass('has-success');
            }
        },
        errorElement: "span",
        errorPlacement: function (error, element) {
            if (element.is(":radio") || element.is(":checkbox")) {
                error.appendTo(element.parent().parent().parent());
            } else if( element.parent().hasClass('input-group') ) {
                error.appendTo(element.parent().parent());
            } else {
                error.appendTo(element.parent());
            }
        },
        errorClass: "help-block m-b-none",
        validClass: "help-block m-b-none"
    });

    //form绑定
    $('form.form_modal').submit(function () {
        var $curForm = $(this);

        if( $curForm.valid() ){
            $curForm.ajaxSubmit(function(json){
                if(json.result == "success"){
                    bootbox.success(json.msg);
                    $curForm.parents('div.modal.inmodal').modal('hide');
                }else{
                    bootbox.error(json.msg);
                }
                $curForm.find('button.modal-submit').removeAttr('disabled');
            });
        }

        return false;
    });


    $('#callbar_dnd').on('click', function () {
        callbar_dnd();
    });

    $('#callbar_idle').on('click', function () {
        callbar_idle();
    });

    $('#callbar_call').on('click', function () {

        $('#modalCall').modal('show');
        $('#modalCall').find('form button.modal-submit').removeAttr('disabled');

        var icon = "<i class='fa fa-times-circle'></i> ";
        $('#modalCall').find('form.form_modal').validate({
            submitHandler: function(form){
                $(form).find('button.modal-submit').attr('disabled', 'disabled');
            },
            rules: {
                callee_phone: {
                    required: true,
                    callee_str: true
                }
            },
            messages: {
                callee_phone: {
                    required: icon + "请输入要呼叫的电话号码",
                    callee_str: icon + "非法电话号码"
                }
            }
        });

    });


    $('#callbar_transfer').on('click', function () {
        $('#transfer_phone').val('');
        $('#modalTransfer').modal('show');
        $('#modalTransfer').find('form button.modal-submit').removeAttr('disabled');


        var icon = "<i class='fa fa-times-circle'></i> ";
        $('#modalTransfer').find('form.form_modal').validate({
            submitHandler: function(form){
                $(form).find('button.modal-submit').attr('disabled', 'disabled');
            },
            rules: {
                transfer_phone: {
                    required: true,
                    callee_str: true
                }
            },
            messages: {
                transfer_phone: {
                    required: icon + "请输入要转到的号码",
                    callee_str: icon + "非法号码"
                }
            }
        });

    });

    $('#callbar_holdon').on('click', function () {
        var statusDisplay = $(this).find('span').html();
        if(statusDisplay == '保持'){
            callbar_holdon();
        }else if(statusDisplay == '恢复'){
            callbar_restore();
        }
    });

    $('#callbar_hangup').on('click', function () {
        callbar_hangup();
    });

    $('#callbar_meet').on('click', function () {

        $('#modalMeet').modal('show');
        $('#modalMeet').find('form button.modal-submit').removeAttr('disabled');

        var icon = "<i class='fa fa-times-circle'></i> ";
        $('#modalMeet').find('form.form_modal').validate({
            submitHandler: function(form){
                $(form).find('button.modal-submit').attr('disabled', 'disabled');
            },
            rules: {
                invite_phone: {
                    required: true,
                    callee_str: true
                }
            },
            messages: {
                invite_phone: {
                    required: icon + "请输入要邀请的电话号码",
                    callee_str: icon + "非法电话号码"
                }
            }
        });

    });

    $('#callbar_score').on('click', function () {
        callbar_score();
    });

});

//弹窗操作函数
function  popMenu(mid, callbackFunc, callbackParams) {
    if( $('iframe[name="iframe-'+ mid +'"]').length===0 ){
        creatNewIframe(mid, "/order/index.html").on('load', function () {
            callbackFunc(mid,callbackParams);
        });
    }else{
        //激活当前iframe
        $('#tab-menu > .tab-item-btn[data-id="iframe-'+ mid +'"]')[0].click();
        callbackFunc(mid,callbackParams);
    }
}

//打开编辑订单窗口
function editOrder(mid,params) {
    $('iframe[name="iframe-14"]')[0].contentWindow.handleEdit(params);
}


function clickcall(callee_phone){
    $.ajax({
        type: 'POST',
        url: '/call_center/clickcall.html',
        data: {callee_phone:callee_phone},
        dataType: 'json',
        success: function (json) {
            if(json.result=='success'){
                bootbox.success(json.msg);
            }else{
                bootbox.error(json.msg);
            }
        }
    });

}